import Vue from 'vue'
import Router from 'vue-router'
import bus from './bus'

Vue.use(Router);

const routes = [
  {
    path: '*',
    redirect: '/home'
  },
  {
    name: 'home',
    component: () => import('./views/home'),
    meta: {
      title: '首页'
    }
  },
  {
    name: 'classification',
    component: () => import('./views/classification'),
    meta: {
      title: '分类'
    }
  },
  {
    name: 'carts',
    component: () => import('./views/carts'),
    meta: {
      title: '购物车'
    }
  },
  {
    name: 'user',
    component: () => import('./views/user'),
    meta: {
      title: '会员中心'
    }
  },
  {
    name: 'goods/:id',
    component: () => import('./views/goods'),
    meta: {
      title: '商品详情'
    },
    props: true
  },
  {
    name: 'search',
    component: () => import('./views/search'),
    meta: {
      title: '搜索'
    }
  },
  {
    name: 'order-list',
    component: () => import('./views/order-list'),
    meta: {
      title: '我的订单'
    }
  },
  {
    name: 'order-submit',
    component: () => import('./views/order-submit'),
    meta: {
      title: '确认订单'
    }
  },
  {
     name: 'order-details',
     component: () => import('./views/order-details'),
     meta: {
       title: '订单详情'
  }
  },
  {
    name: 'address',
    component: () => import('./views/address'),
    meta: {
      title: '地址管理'
    }
  },
  {
    name: 'address-edit',
    component: () => import('./views/address/edit'),
    meta: {
      title: '地址编辑'
    }
  },
  {
    name: 'pay',
    component: () => import('./views/pay'),
    meta: {
      title: '支付'
    }
  },
  {
    name: 'login',
    component: () => import('./views/login'),
    meta: {
      title: '欢迎登录'
    }
  },
  {
    name: 'logout',
    meta: {
      title: '退出登录'
    }
  }
];

// add route path
routes.forEach(route => {
  route.path = route.path || '/' + (route.name || '');
});

const router = new Router({ routes });

router.beforeEach((to, from, next) => {
  if(to.path.includes('logout')){
    bus.state.token=undefined;
    next('/login');
  }
  const title = to.meta && to.meta.title;
  if (title) {
    document.title = title;
  }
  next();
});

export default router
